#include <stdio.h>
#include <getch.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>

#define BUF_SIZE (4096)
typedef struct sockaddr* SAP;

int main()
{
	int sock = socket(AF_INET,SOCK_DGRAM,0);
	if(0 > sock)
	{
		perror("socket");
		return EXIT_FAILURE;
	}
	
	struct sockaddr_in addr = {}, from_addr_1 = {}, from_addr_2 = {};
	addr.sin_family = AF_INET;
	addr.sin_port = htons(10077);
	addr.sin_addr.s_addr = inet_addr("172.20.10.3"); //172.20.10.3 47.110.244.211
	socklen_t addrlen = sizeof(addr);
	
	if(bind(sock,(SAP)&addr,addrlen))
	{
		perror("bind");
		close(sock);
		return EXIT_FAILURE;
	}
	
	char buf[BUF_SIZE] = {};
	//接收先手棋手
	recvfrom(sock,buf,BUF_SIZE,0,(SAP)&from_addr_1,&addrlen);
	printf("%s\n",buf);
	sprintf(buf,"F:你是先手,请等待下一位选手链接");
	sendto(sock,buf,strlen(buf)+1,0,(SAP)&from_addr_1,addrlen);
	
	//等待后手棋手
	recvfrom(sock,buf,BUF_SIZE,0,(SAP)&from_addr_2,&addrlen);
	printf("%s\n",buf);
	sprintf(buf,"B:你是后手");
	sendto(sock,buf,strlen(buf)+1,0,(SAP)&from_addr_2,addrlen);
	
	//游戏开始
	sprintf(buf,"双方就绪，3s后游戏开始");
	sendto(sock,buf,strlen(buf)+1,0,(SAP)&from_addr_1,addrlen);
	sendto(sock,buf,strlen(buf)+1,0,(SAP)&from_addr_2,addrlen);
	
	int ret_size;
	for(;;)
	{
		ret_size = recvfrom(sock,buf,BUF_SIZE,0,(SAP)&from_addr_1,&addrlen);
		sendto(sock,buf,strlen(buf)+1,0,(SAP)&from_addr_2,addrlen);
		recvfrom(sock,buf,BUF_SIZE,0,(SAP)&from_addr_2,&addrlen);
		sendto(sock,buf,strlen(buf)+1,0,(SAP)&from_addr_1,addrlen);				
	}
}
